
const pgp = require('pg-promise')();
var monitorSubKey = null
var webClientPubKey = null
var Mqtt = require( 'mqtt')
module.exports = agent =>{

    agent.messenger.on( 'egg-ready', async ()=>{

        var pgdb = pgp( agent.config.database.pg );
        var protectors = await pgdb.query( "SELECT * from protectors " );
        console.log( protectors );
        var alarm_log = await pgdb.query( "SELECT * from protector_alarm_log" );
        console.log( alarm_log );


        var mqtt = Mqtt.connect( "mqtt://" + agent.config.mqtt.host );

        mqtt.on( "connect" , ( ack )=> {
            console.log( "connect ", agent.config.mqtt.host , " success !" );
        });

        mqtt.subscribe( "start/#")
        mqtt.subscribe( "webServer/alarm/#" )
        mqtt.on('message',async ( topic, payload, packet )=>{
            console.log( "_____________ mqtt, " + topic + " _________" );

            var msg  = JSON.parse( payload.toString() )
            console.log( topic , ":" ,  msg )
            var parts = topic.split( "/")
            console.log( parts );
            if( parts[0] == "start" ) {
                console.log( "new  device presented !!" );
                var ip = parts[1];
                var mac = parts[2];
                var protectors  = await pgdb.query( "SELECT mac, shopid, ip FROM protectors WHERE mac = $1", [mac] );
                if( protectors.length > 0 ) {
                    //have been exist
                    if( ip != protectors[0].ip ) {
                        await pgdb.query( "UPDATE protectors SET ip = $1 ", [ ip ] )
                    }
                } else {
                    await pgdb.query( "INSERT INTO protectors( mac, ip, detail   ) VALUES( $1, $2, $3 ) ", [mac, ip, { vendor: "福克斯" } ] );
                }
            }
            else if( parts[0] == "webServer" && parts[1] == "alarm" ) {
                try{

                    var mac = parts[2];
                    var arm_area_idx = Object.keys( msg )[0];
                    var shop = await pgdb.one( "SELECT shopid from protectors WHERE mac = $1 ", [ mac ] );


                    if( shop.shopid ) {
                        await pgdb.query( "INSERT INTO protector_alarm_log( shopid, mac, stamp, arm_area_idx )  VALUES( $1, $2, $3, $4 ) ", [ shop.shopid, mac, msg[arm_area_idx], arm_area_idx ] );
                        mqtt.publish( 'monitor/alarmLog/' + mac , JSON.stringify( { shopid: shop.shopid, mac: mac, arm_area_idx: arm_area_idx, stamp:  msg[arm_area_idx] } ) );
                    }
                }
                catch ( error ) {
                    console.log( 'error: -----------', error );
                }
            }
            else{
                console.log( "unexpected messge" );
            }
        });
        console.log( "agent is ok !" )
    })
}


/*

    if( topic.match( /^monitor\/(.*)\/(.*)\/(.*)$/ ) ) {

        var all = topic.split( "/" )

        //var monitor = all[0]
        var ip = all[1]
        var mac = all[2].replace( /\:/g, "" )
        var channel = all[3]

        try{

            //if exist
            if( all_devices[mac] === undefined  ) {
                //no exist , add new device
                console.log( "add new device: ", ip, " , ",  mac  )
                all_devices[ mac ] = {}
                mqtt.publish( "device/" + mac, "b" )
                setTimeout( () => {
                    mqtt.publish( "device/" + mac, "d" );
                }, 2000 );

                await pgdb.query( "INSERT INTO protectors( mac, ip, arm_areas )  VALUES( $1, $2, $3 ) " , [ mac, ip, {} ] )
            }

            if( channel == "notReady" ) {
                console.log( mac, " 撤防状态显示 ", Object.keys( msg ), "防区有干扰" )
            }
            else if( channel == "alarm"  ) {

                //arm_area : {
                //   s: "b"/"c"
                //   t: Date.now //布防撤防的时间
                //   a: Date.now()//报警时间
                //   l: //楼层编号
                //   x, y: //布局图上的location
                //}
                //

                var ret_array = await pgdb.query( 'SELECT arm_areas FROM protectors WHERE mac = $1 ', [ mac ]  );
                if( ret_array.length  == 0 ) {
                    return;
                }

                arm_areas = ret_array[0].arm_areas;

                console.log( "get alarm msg: ", msg );
                for( let idx in msg ) {
                    if( !arm_areas[idx] ) {
                        arm_areas[idx] = {}
                    }
                    arm_areas[idx ].a = Date.now()
                    await pgdb.none( "INSERT INTO protector_op_log( stamp, op, arm_area_idx, mac ) VALUES( $1, $2, $3 , $4) ", [ Date.now(), "alarm", idx, mac ] )
                    mqtt.publish( "webClient/" + mac, JSON.stringify( { mac: mac, alarm: idx } ));
                }
                console.log( mac , " 报警:", msg )
                await pgdb.none( "UPDATE protectors SET arm_areas = $1 WHERE  $2 = mac ", [ arm_areas, mac ] )
            }
            else if( channel == "panglu" ) {
                console.log( mac, " 旁路", msg );
                for( let idx in msg ) {
                    if( !arm_areas[idx] ) {
                        arm_areas[idx] = {}
                    }
                    arm_areas[idx].s = "c";
                    arm_areas[idx].t = Date.now()
                    await pgdb.none( "INSERT INTO protector_op_log( stamp, op, arm_area_idx, mac ) VALUES( $1, $2, $3 ) ", [ Date.now(), "chefang", idx, mac ] )
                }
                mqtt.publish( "webClient/" + mac, JSON.stringify( { mac: mac, bypass: idx } ) );
                console.log( mac , " 报警:", msg )
                await pgdb.query( "UPDATE  protectors SET arm_areas = $1 WHERE $2 = mac " , [ arm_areas, mac ] )
            }
            else if( channel == "bufang") {
                console.log( mac , " 布防" , msg );
            }
            else if( channel == "chefang" ){
                console.log( mac, " 撤防", msg  );
            }
            else {
                console.error( "unexpected message" );
            }

        }
        catch( error ) {
            console.log( error );
        }
    }
    else if( topic.match( /^start\/(.*)\/(.*)$/ ) ) {
        var all = topic.split( "/" );
        var ip = all[1]
        var mac = all[2]
        //if exist
        if( all_devices[mac] === undefined ) {
            //no exist , add new device
            console.log( "----------------------  add new device: ", ip, " , ",  mac  )
            all_devices[ mac ] = {}
            await pgdb.query( "INSERT INTO protectors( mac, ip, arm_areas )  VALUES( $1, $2, $3 ) " , [ mac, ip, {} ] )
        }
    }
    else if( topic == "monitor/devices" ) {
        var msg = JSON.parse( payload.toString() );
        for( let mac in msg ) {
            var ip = msg[mac].ip;
            var arm_areas = msg[mac].arm_areas;
            var ret_array = await pgdb.any( "SELECT arm_areas from protectors WHERE mac = $1 ", [mac] );
            if( rea_array.length > 0 ) {
                var old_arm_areas = ret_array[0].arm_areas;

                for( let idx in arm_areas ) {
                    old_arm_areas[idx].s = arm_areas[idx].s;
                    old_arm_areas[idx].t = arm_areas[idx].t;
                    old_arm_areas[idx].a = arm_areas[idx].a;
                }

                pgdb.query( "UPDATE protectors SET arm_areas = $1 WHERE mac = $2 " , [ new_arm_areas, mac] );
            }
            else {
                pgdb.query( "INSERT INTO protectors( mac, ip )  VALUES( $1, $2 )", [ mac, ip  ] );
            }
        }
    }
    else {
        console.error( "unexpectd topic " );
    }
*/
